package com.huxiu.yd;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.Comment;
import com.huxiu.yd.net.responses.BaseResponse;
import com.huxiu.yd.net.responses.CommentsResponse;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.AvatarView;
import com.huxiu.yd.view.CommentViewHolder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class CommentActivity extends BaseActivity implements OnRefreshListener2<ListView> {

    Comment comment;

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.send_button)
    TextView sendButton;

    @InjectView(R.id.review_edit)
    EditText commentEdit;

    AvatarView avatar;

    TextView name;

    TextView time;

    TextView content;

    TextView dianpingCount;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    View commentHeaderContainer;

    private int type;

    private static final int TYPE_DISCOVERY = 0;

    private static final int TYPE_SPARE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ButterKnife.inject(this);
        comment = (Comment) getIntent().getSerializableExtra("comment");
        LogUtils.d("comment is " + comment);
//        boolean shouldShowKeyBoard = getIntent().getBooleanExtra("show_keyboard", false);
//        if (shouldShowKeyBoard) {
//            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        type = getIntent().getIntExtra("is_discovery", TYPE_DISCOVERY);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText(R.string.comment);
        adapter = new CommentAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setState(State.INIT_REFRESHING, true);
        sendButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(commentEdit.getText().toString())) {
                    submitComment();
                }
            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getComments();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

    }

    private void submitComment() {
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "add_comment");
        params.put("comment_id", comment.id);
        String url;
        if (type == TYPE_DISCOVERY) {
            url = NetworkConstants.DISCOVERY_URL;
            params.put("article_id", comment.article_id);
        } else {
            url = NetworkConstants.GOODS_URL;
            params.put("user_goods_id", comment.user_goods_id);
        }
        params.put("comment", commentEdit.getText().toString());
        LogUtils.d("submitComment, content is " + params);
        LogUtils.d("submitComment, url is " + url);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Method.POST, BaseResponse.class,
                true, params, new Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.isSuccess()) {
                    Utils.showToast(R.string.submit_comment2_success);
                    list.setState(State.INIT_REFRESHING, true);
                    commentEdit.setText("");
                    Utils.closeKeyboard(commentEdit);
                } else {
                    Utils.showToast(response.msg);
                }
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
        showProgress();
    }

    private void getComments() {
        String url = type == TYPE_DISCOVERY ? NetworkConstants.DISCOVERY_URL
                : NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("comment_id", comment.id);
        params.put("act", "reply_comment");
        GsonRequest<CommentsResponse> request = new GsonRequest<>(url, Method.POST,
                CommentsResponse.class, false, params, new Listener<CommentsResponse>() {
            @Override
            public void onResponse(CommentsResponse response) {
                refreshComplete();
                if (response.isSuccess()) {
                    comments.clear();
                    Collections.addAll(comments, response.data);
                    adapter.notifyDataSetChanged();
                }
            }
        }, mErrorListener);
        mQueue.add(request);
        mQueue.start();
    }

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);

    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            refreshComplete();
            dismissProgress();
            Throwable t = error.getCause();
            if (!(t instanceof ErrorResponseException)) {
                Utils.showToast(R.string.generic_failure);
            }
        }
    };

    private List<Comment> comments = new ArrayList<>();

    private CommentAdapter adapter;

    private class CommentAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return comments.size() + 1;
        }

        @Override
        public Comment getItem(int position) {
            return position == 0 ? null : comments.get(position - 1);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0) return 0;
            else return 1;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == 0) {
                convertView = getLayoutInflater().inflate(R.layout.comment_header_layout, parent, false);
                name = ButterKnife.findById(convertView, R.id.name);
                name.setText(comment.name);
                time = ButterKnife.findById(convertView, R.id.time);
                time.setText(Utils.getDateString(comment.create_time));
                content = ButterKnife.findById(convertView, R.id.content);
                content.setText(comment.content);
                dianpingCount = ButterKnife.findById(convertView, R.id.dianping_count);
                dianpingCount.setVisibility(View.GONE);
                commentHeaderContainer = ButterKnife.findById(convertView, R.id.comment_header_container);
                commentHeaderContainer.setVisibility(View.GONE);
                avatar = ButterKnife.findById(convertView, R.id.avatar);
                avatar.setUserInfo(comment.user_id, comment.avatar, comment.name);
                return convertView;
            } else {
                View view = convertView;
                CommentViewHolder vh;
                if (view == null) {
                    view = getLayoutInflater().inflate(R.layout.comment_list_item, parent, false);
                    vh = new CommentViewHolder(view);
                    view.setTag(vh);
                }
                vh = (CommentViewHolder) view.getTag();
                Comment comment = getItem(position);
                vh.header.setVisibility(position == 1 ? View.VISIBLE : View.GONE);
                vh.bottomDivider.setVisibility(View.VISIBLE);
                vh.avatar.setUserInfo(comment.user_id, comment.avatar, comment.name);
                vh.commentHeader.setText(getString(R.string.dianping) + "  (" + comments.size() + ")");

                vh.name.setText(comment.name);
                vh.time.setText(Utils.getDateString(comment.create_time));
                vh.content.setText(comment.content);
                vh.dianpingCount.setVisibility(View.GONE);
                return view;
            }
        }
    }
}
